使用 R 中的 Lines() 函数在绘图中添加一条线 您所在的位置:网站首页 rstudio plot函数 使用 R 中的 Lines() 函数在绘图中添加一条线

使用 R 中的 Lines() 函数在绘图中添加一条线

2024-07-15 22:38| 来源: 网络整理| 查看: 265

在 R 中使用 lines() 函数的绘图中添加一条线 在 R 中使用 points 的绘图中添加点 plot 和 lines 函数调用顺序影响绘图的比例

本文将介绍如何使用 R 中的 lines() 函数在绘图中添加一条线。

在 R 中使用 lines() 函数的绘图中添加一条线

lines() 函数是 R graphics 包的一部分,用于向绘图添加线条。首先,应该调用 plot 函数来构造一个图,其中有一个由前两个参数指定的变量映射。请注意,表示 y 轴坐标的第二个参数是可选的。绘制绘图后,我们可以调用 lines() 函数并根据需要传递坐标向量以将线条添加到绘图中。plot 函数不需要为 lines() 函数绘制折线图。

library(stats) library(babynames) library(dplyr) plot(cars$speed, cars$dist, type = "l", col = "red", main = "Title of the Plot", xlab = "Speed (mph)", ylab = "Stopping Distance (Feet)") lines(cars$speed, cars$dist/4 , col = "green") legend("topleft", c("line 1", "line 2"), lty = c(1,1), col = c("red", "green"))

在 R 中使用 points 的绘图中添加点

与 lines() 函数类似,graphics 包提供了 points() 函数来在图中绘制点。以下示例演示了在同一绘图上进行两条线和点映射的场景。但是请注意,原始折线图是使用 plot 函数绘制的。

library(stats) library(babynames) library(dplyr) plot(cars$speed, cars$dist, type = "l", col = "red", main = "Title of the Plot", xlab = "Speed (mph)", ylab = "Stopping Distance (Feet)") points(cars$speed, cars$dist, col = "blue" ) lines(cars$speed, cars$dist/4 , col = "green") points(cars$speed, cars$dist/4 , col = "black") legend("topleft", c("line 1", "line 2"), lty = c(1,1), col = c("red", "green"))

plot 和 lines 函数调用顺序影响绘图的比例

有时,使用第一个函数调用映射的数据的比例不足以进行后续映射。下一个代码片段显示其中一条线几乎超出了图中的边界。

library(stats) library(babynames) library(dplyr) dat % filter(name %in% c("Alice")) %>% filter(sex=="F") dat2 % filter(name %in% c("Mary")) %>% filter(sex=="F") plot(dat$year, dat$n, type = "l", col = "blue", main = "Women born with different names", xlab = "Year", ylab = "Number of babies born") lines(dat2$year, dat2$n, col = "red")

请注意,可以通过手动重新排序行来解决上一个问题,如下例所示。但是,更复杂的脚本可能需要构造条件语句并动态检查 y 轴数据的最大值。

library(stats) library(babynames) library(dplyr) dat % filter(name %in% c("Alice")) %>% filter(sex=="F") dat2 % filter(name %in% c("Mary")) %>% filter(sex=="F") dat3 % filter(name %in% c("Mae")) %>% filter(sex=="F") plot(dat2$year, dat2$n, type = "l", col = "blue", main = "Women born with different names", xlab = "Year", ylab = "Number of babies born") lines(dat$year, dat$n, col = "red") lines(dat3$year, dat3$n, col = "orange") legend("topright", c("Mary", "Alice", "Mae"), lty = c(1,1,1), col = c("blue", "red", "orange"))



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有